<?php

namespace app\api\model;

use app\admin\event\SystemLog;
use app\admin\model\Admin;
use think\exception\DbException;
use think\Model;
use think\Db;

class SaleModel extends Base
{
    // 状态
    //5待出库
    const toBeOutOfTheLibrary = 5;
    //  1部分出库
    const partialOutbound = 1;
    // 2已撤销
    const cancel = 2;
    // 3草稿
    const draft = 3;
    //  4已出售
    const itHasBeenSold = 4;

    protected static function init()
    {
        self::observe(SystemLog::class);
    }

    protected $table = 'jxc_sale';

    public function getModelAttr($value)
    {
        // 0自提 1送车 2送指定地点 3发物流 4电子面单
        switch ($value) {
            case 0:
                return '自提';
            case 1:
                return '送车';
            case 2:
                return '送指定地点';
            case 3:
                return '发物流';
            case 4:
                return '电子面单';
            default:
                return '无效的发货方式';
        }
    }

    // 定义全局的查询范围
    protected function base($query)
    {
        $c = Admin::find(\app\http\GetUid::getUId());
        // 门店负责人可查看自己门店的所有信息
        if ($c->level == 2) {
            $maker = Admin::where('store', $c->store)->where('level', 3)->column('id');
        } elseif ($c->level == 1) {
            $maker = Admin::column('id');
        } else {
            $maker = $c->id;
        }
        $query->whereIn('maker', $maker);
    }

    public function getStatusAttr($value)
    {
        //状态 1部分出库 2已撤销 3草稿 4已出售 5待出库
        switch ($value) {
            case 1:
                return '部分出库';
            case 2:
                return '已撤销';
            case 3:
                return '草稿';
            case 4:
                return '已出售';
            default:
                return '待出库';
        }
    }

    /**
     * 前台收银 状态
     * @param $value
     * @return string
     */
    private static function getCollectStatusAttr($value)
    {
//        状态 1已零售 2已撤销
        switch ($value) {
            case 1:
                return '已零售';
            case 2:
                return '已撤销';
            default:
                return '无效的状态';
        }
    }

    /**
     * @param $value
     * @return mixed
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSetAccountAttr($value)
    {
        // 结算账户 0支付宝 1微信 2银行卡
        return DB::name('set_account')->where(['status' => 0, 'id' => $value])->find()['name'];
    }

//    public function getPaymentModeAttr($value)
//    {
//
//    }

    /**
     * @param $data
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getSaleList($data)
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where[] = ['create_time', 'between', [$data['start_time'], $data['end_time']]];
        }
        if (!empty($data['sales'])) {
            $where[] = ['sales', '=', $data['sales']];
        }
        if (!empty($data['kid'])) {
            $where[] = ['kid', '=', $data['kid']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number', 'like', "%" . $data['number'] . "%"];
        }
        if (!empty($data['courier'])) {
            $where[] = ['courier', 'like', "%" . $data['courier'] . "%"];
        }
        $list = Sale::where($where)->page($data['page'],$data['size'])->paginate($data['size']);
        //     'sale',
        //     $where,
        //     'id desc',
        //     $data['page'],
        //     $data['size']
        // );
        // var_dump($list);exit();
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list['data'][$k]['kid'] = $this->getValue('user', ['id' => $v['kid']], 'name');
            $list['data'][$k]['warehouse'] = $this->getValue('warehouse', ['id' => $v['warehouse']], 'name');
            $list['data'][$k]['sales'] = \app\admin\model\Admin::find($v['sales'])['name'];
            $list['data'][$k]['set_account'] = $this->getValue('set_account', ['id' => $v['set_account']], 'name');
            $v['status'] = $this->getStatusAttr($v['status']);
        }
        return $list;
    }

    /**
     * @param $data
     * @return int|string
     */
    public function getSaleAdd($data)
    {
        $arr = $this::create($data);
        if ($data['status'] == 5) {
            $stock['status'] = 1;
            $stock['number'] = $data['number'];
            $stock['create_time'] = $data['create_time'];
            $stock['kid'] = $data['kid'];
            $stock['mode'] = $data['mode'];
            $stock['mode_address'] = $data['mode_address'];
            $stock['account_type'] = $data['type'];
            $stock['money'] = $data['money'];
            $stock['warehouse'] = $data['warehouse'];
            $stock['maker'] = $data['maker'];
            $stock['type'] = 1;//单据类型 1销售单 2配货单 3调拨单
            $stock['des'] = !isset($data['des']) ? '' : $data['des'];
            $stock['relation_id'] = $arr->id;
            $this->getAdd('outstock', $stock);
            foreach ($data['goods'] as $k => $v) {
                $relation['product_id'] = $v['product_id'];
                $relation['put_number'] = $v['put_number'];
                $relation['pid'] = $arr->id;
                $relation['price'] = $v['price'];
                $relation['discount'] = $v['discount'];
                $relation['discount_price'] = $v['discount_price'];
                $relation['money'] = $v['money'];
                $relation['discount_money'] = $v['discount_money'];
                $relation['create_time'] = time();
                $this->getAdd('salerelation', $relation);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'put_out' => $v['put_number']
                    ];
                    $this->getAdd('product_stock', $rel);
                }else{
                    $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'put_out',$v['put_number']);
                }
            }
        }else{
            foreach ($data['goods'] as $k => $v) {
                $relation['product_id'] = $v['product_id'];
                $relation['put_number'] = $v['put_number'];
                $relation['pid'] = $arr->id;
                $relation['price'] = $v['price'];
                $relation['discount'] = $v['discount'];
                $relation['discount_price'] = $v['discount_price'];
                $relation['money'] = $v['money'];
                $relation['discount_money'] = $v['discount_money'];
                $relation['create_time'] = time();
                $this->getAdd('salerelation', $relation);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'stock' => 0
                    ];
                    $this->getAdd('product_stock', $rel);
                }
            }
        }
        return $arr;
    }

    /**
     * @param $id
     * @return array|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSaleInfo($id)
    {
        $list = $this->getOne('sale', '*', ['id' => $id]);
        if (is_null($list)) {
            return false;
        }
        $list['goods'] = $this->getselectList('salerelation', '*', ['pid' => $list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $dan = $this->getOne('product', 'commodity_id,color,size', ['id' => $v['product_id']]);
            $goods = $this->getOne('commodity', 'id,name,item,goods_code,unit', ['id' => $dan['commodity_id']]);
            $list['goods'][$k]['name'] = $goods['name'];
            $list['goods'][$k]['item'] = $goods['item'];
            $list['goods'][$k]['goods_code'] = $goods['goods_code'];
            $list['goods'][$k]['dismoney'] = $v['discount_money'];
            $list['goods'][$k]['disprice'] = $v['discount_price'];
            $list['goods'][$k]['color'] = $this->getValue('color3', ['id' => $dan['color']], 'name');
            $list['goods'][$k]['size'] = $this->getValue('color3', ['id' => $dan['size']], 'name');
            $list['goods'][$k]['unit'] = $this->getValue('color1', ['id' => $goods['unit']], 'name');
            $list['goods'][$k]['commodity_id'] = $goods['id'];
        }
        $list['kid_name'] = $this->getValue('user', ['id' => $list['kid']], 'name');
        $list['kid_phone'] = $this->getValue('user', ['id' => $list['kid']], 'phone');
        $list['warehouse_name'] = $this->getValue('warehouse', ['id' => $list['warehouse']], 'name');
        $list['sales_name'] = $this->getValue('admin', ['id' => $list['sales']], 'name');
        $list['mode_name'] = $this->getModelAttr($list['mode']);
        $list['set_account_name'] = $this->getSetAccountAttr($list['set_account']);
        $list['images'] = json_decode($list['images']);
        $list['address'] = json_decode($list['mode_address']);
        $user = $this->getOne('admin', 'name,phone', ['id' => $list['maker']]);
        $list['maker_name'] = $user['name'];
        $list['maker_phone'] = $user['phone'];
        $list['create_time'] = date('Y-m-d H:i:s',$list['create_time']);
        $list['status_name'] = $this->getStatusAttr($list['status']);
        $list['type1'] = '销售单';
        $list['type_name'] = $this->getValue('account_type', ['id' => $list['type']], 'name');
        //关联出库表id
        $outstock_id = db('outstock')->where(['relation_id' => $id])->column('id');
        $list['outstock_id'] = !empty($outstock_id) ? $outstock_id[0] : 0;
        
        return $list;
    }

    /**
     * @param $id
     * @return array|int|\PDOStatement|string|Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getSaleDel($id)
    {
        $list = Db::name('sale')->find($id);
        $status = $list['status'];
        switch ($status) {
            case self::draft:
                Db::startTrans();
                try {
                    $arr[] = $this->getDel('sale', $id);
                    $arr[] = Db::name('salerelation')->whereIn('pid', $id)->delete();
                    Db::commit();
                    return $arr;
                } catch (DbException $e) {
                    Db::rollback();
                    return $e->getMessage();
                }
            case self::toBeOutOfTheLibrary:
                //TODO:: 待出库要删除 出库表记录
                return Db::transaction(function () use ($id, $list) {
                    // 查找 销售关联表记录并删除
                    $r = Db::name('salerelation')->field('id')->where('pid', $id)->select();
                    $rId = array_map(function ($item) {
                        return $item['id'];
                    }, $r);
                    $res[] = (count($rId) > 0) ? Db::name('salerelation')->whereIn('id', $rId)->delete() : false;
                    // 查找 出库表 销售 记录并删除
                    $o = Db::name('outstock')->field('id')
                        ->where('type', 1)->whereIn('relation_id', $rId)->where('type', 1)->select();
                    $oId = array_map(function ($item) {
                        return $item['id'];
                    }, $o);
                    $res[] = (count($oId) > 0) ? Db::name('outstock')->whereIn('id', $oId)->delete() : false;
                    // 删除销售表记录
                    $res[] = Db::name('sale')->delete(['id' => $list['id']]);
                    return $res;
                });
//            case self::partialOutbound:
//                break;
//            case self::cancel:
//            case self::itHasBeenSold:
            default:
                return 2;
        }
    }

    /**
     * @param $data
     * @return int|string
     */
    public function addMessage($data)
    {
        return $this->getAdd('message', $data);
    }

    /**
     * @param string $sid
     * @param int $page
     * @param int $size
     * @return string|\think\Paginator
     */
    public function getMessageList($data)
    {
        $where =[];
        if (!empty($data['pid'])) {
            $where[] = ['pid','=',$data['pid']];
        }
        if (!empty($data['type'])) {
            $where[] = ['type','=',$data['type']];
        }
        try {
            return Db::name('message')->where($where)->page($data['page'], $data['size'])->paginate($data['size'])
            ->each(function($item){
                $item['create_time'] =date('Y-m-d',$item['create_time']);
                return $item;
            });
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getMessage($data)
    {
        $where =[];
        if (!empty($data['pid'])) {
            $where[] = ['pid','=',$data['pid']];
        }
        if (!empty($data['type'])) {
            $where[] = ['type','=',$data['type']];
        }
        return Db::name('message')->where($where)->order('create_time desc')->limit(1)->find();
    }

    /**
     * @param $id
     * @return int
     */
    public function MessageDel($id)
    {
        return $this->getDel('message', $id);
    }

    /**
     * 销售订单 撤销
     * @param $id
     * @return array|int|\PDOStatement|string|Model|null
     */
    public function getSaleRevoke($id)
    {
        try{
            $list =$this->getOne('sale','*',['id'=>$id]);
            if(in_array($list['status'],[1,2,4])){
                throw new \Exception('单据已出库,无法撤销');
            }else{
                if($list['status'] ==5){
                    $this->getSetField('outstock',array('relation_id'=>$id,'type'=>1),['status'=>4]);
                }
                return $this->getSetField('sale',['id'=>$id],['status'=>2]);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 全部出库
     * @param $id
     * @return string|\think\response\Json
     */
    public function getAllDepot($id)
    {
        $list = $this->getOne('sale', '*', ['id' => $id]);
        $list['goods'] = $this->getselectList('salerelation', '*', ['pid' => $list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $this->getSetDec('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'stock', $v['put_number']-$v['number']);
            $this->getSetDec('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'put_out', $v['put_number']-$v['number']);
            $this->getSetField('salerelation', ['id' => $v['id']], ['number' => $v['put_number']]);
            $stock = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$list['warehouse']], 'stock');
            $flow = [
                'goods_id' => $v['product_id'],
                'create_time' => time(),
                'warehouse' => $list['warehouse'],
                'type' => '销售单',
                'number' => $list['number'],
                'add_num' => '-' . $v['put_number'],
                'sur_num' => $stock - $v['put_number']
            ];
            $this->getAdd('flowing_water', $flow);
        }
        $payment =[
            'customer_id' => $list['kid'],
            'customer_type' => 'user',
            'maker' => $list['maker'],
            'set_account' => $list['set_account'],
            'account_type_id' => $list['type'],
            'in_amount' => $list['payment'],
            'des' => $list['des'],
            'create_time' => time(),
            'images' => $list['images'],
            'payment_mode' => $list['payment_mode'],
            'business_type' => '销售单',
            'business_number' => $list['number'],
            'business_time' => $list['create_time'],
        ];
        $this->getAdd('set_account_flow', $payment);
        $this->getSetField('outstock', array('relation_id' => $id, 'type' => 1), ['status' => 3]);
        return $this->getSetField('sale', ['id' => $id], ['status' => 4]);
    }

    public function getDraft($id, $data)
    {
        $list = $this->getEdit('sale', ['id' => $id], $data);
        Db::name('salerelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k => $v) {
            $relation['product_id'] = $v['product_id'];
            $relation['put_number'] = $v['put_number'];
            $relation['pid'] = $id;
            $relation['price'] = $v['price'];
            $relation['discount'] = $v['discount'];
            $relation['discount_price'] = $v['discount_price'];
            $relation['money'] = $v['money'];
            $relation['discount_money'] = $v['discount_money'];
            $relation['create_time'] = time();
            $this->getAdd('salerelation', $relation);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'stock' => 0
                ];
                $this->getAdd('product_stock', $rel);
            }
        }
        return $list;
    }

    public function getPutStock($id, $data)
    {
        $this->getEdit('sale', ['id' => $id], $data);
        Db::name('salerelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k => $v) {
            $relation['product_id'] = $v['product_id'];
            $relation['put_number'] = $v['put_number'];
            $relation['pid'] = $id;
            $relation['price'] = $v['price'];
            $relation['discount'] = $v['discount'];
            $relation['discount_price'] = $v['discount_price'];
            $relation['money'] = $v['money'];
            $relation['discount_money'] = $v['discount_money'];
            $relation['create_time'] = time();
            $this->getAdd('salerelation', $relation);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'put_out' => $v['put_number']
                ];
                $this->getAdd('product_stock', $rel);
            }else{
                $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'put_out',$v['put_number']);
            }
        }
        $list = $this->getOne('sale', '*', ['id' => $id]);
        $stock['status'] = 1;
        $stock['number'] = $list['number'];
        $stock['kid'] = $data['kid'];
        $stock['mode'] = $data['mode'];
        $stock['mode_address'] = $data['mode_address'];
        $stock['account_type'] = $data['type'];
        $stock['money'] = $data['money'];
        $stock['create_time'] = $data['create_time'];
        $stock['warehouse'] = $data['warehouse'];
        $stock['maker'] = $data['maker'];
        $stock['type'] = 1;//单据类型 1销售单 2配货单 3调拨单
        $stock['des'] = $data['des'];
        $stock['relation_id'] = $id;
        return $this->getAdd('outstock', $stock);
    }

    /**
     * 销售退货单
     * @param $data
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getReturnList($data)
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where[] = ['create_time', 'between', [$data['start_time'], $data['end_time']]];
        }
        if (!empty($data['sales'])) {
            $where[] = ['sales', '=', $data['sales']];
        }
        if (!empty($data['kid'])) {
            $where[] = ['kid', '=', $data['kid']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number', 'like', "%" . $data['number'] . "%"];
        }
        $list = $this->getPage(
            'salereturn',
            'id,status,number,create_time,kid,warehouse,maker,set_account,payment,des',
            $where,
            'id desc',
            $data['page'],
            $data['size']
        );
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list['data'][$k]['kid'] = $this->getValue('user', ['id' => $v['kid']], 'name');
            $list['data'][$k]['warehouse'] = $this->getValue('warehouse', ['id' => $v['warehouse']], 'name');
            $list['data'][$k]['maker'] = $this->getValue('admin', ['id' => $v['maker']], 'name');
            $list['data'][$k]['set_account'] = $this->getValue('set_account', ['id' => $v['set_account']], 'name');
            switch ($v['status']) {
                case 1:
                    $list['data'][$k]['status1'] = "已退货";
                    break;
                case 2:
                    $list['data'][$k]['status1'] = "已撤销";
                    break;
                default:
                    $list['data'][$k]['status1'] = "草稿";
            }
        }
        return $list;
    }

    /**
     * 销售退货 新增
     * @param $data
     * @return int|string
     */
    public function getReturnAdd($data)
    {
        $arr1 = $this->getAdd('salereturn', $data);
        if ($data['status'] == 1) {
            $stock['status'] = 3;
            $stock['number'] = $data['number'];
            $stock['create_time'] = $data['create_time'];
            $stock['warehouse'] = $data['warehouse'];
            $stock['maker'] = $data['maker'];
            $stock['type'] = 4;//单据类型  4销售退货单
            $stock['des'] = $data['des'];
            $stock['relation_id'] = $arr1;
            $this->getAdd('instock', $stock);
            foreach ($data['goods'] as $k => $v) {
                $arr['goods_status'] = $v['goods_status'];
                $arr['product_id'] = $v['product_id'];
                $arr['put_number'] = $v['put_number'];
                $arr['pid'] = $arr1;
                $arr['price'] = $v['price'];
                $arr['discount'] = $v['discount'];
                $arr['discount_price'] = $v['discount_price'];
                $arr['money'] = $v['money'];
                $arr['discount_money'] = $v['discount_money'];
                $this->getAdd('salereturnrelation', $arr);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'stock' => $v['put_number']
                    ];
                    $this->getAdd('product_stock', $rel);
                }else{
                    $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'stock',$v['put_number']);
                }
                $flow = [
                    'goods_id' => $v['product_id'],
                    'create_time' => time(),
                    'warehouse' => $data['warehouse'],
                    'type' => '销售退货单',
                    'number' => $data['number'],
                    'add_num' => $v['put_number'],
                    'sur_num' => (isset($stockInfo['stock']) ? $stockInfo['stock'] : 0) + $v['put_number']
                ];
                $this->getAdd('flowing_water', $flow);
            }
            $payment =[
                'customer_id' => $data['kid'],
                'customer_type' => 'user',
                'maker' => $data['maker'],
                'set_account' => $data['set_account'],
                'in_amount' => $data['payment'],
                'des' => $data['des'],
                'create_time' => time(),
                'business_type' => '销售退货单',
                'business_number' => $data['number'],
                'business_time' => $data['create_time']
            ];
            $this->getAdd('set_account_flow', $payment);
        } else {
            foreach ($data['goods'] as $k => $v) {
                $arr['goods_status'] = $v['goods_status'];
                $arr['product_id'] = $v['product_id'];
                $arr['put_number'] = $v['put_number'];
                $arr['pid'] = $arr1;
                $arr['price'] = $v['price'];
                $arr['discount'] = $v['discount'];
                $arr['discount_price'] = $v['discount_price'];
                $arr['money'] = $v['money'];
                $arr['discount_money'] = $v['discount_money'];
                $this->getAdd('salereturnrelation', $arr);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'stock' => 0
                    ];
                    $this->getAdd('product_stock', $rel);
                }
            }
        }
        return $arr1;
    }

    public function getReturnDraft($id, $data)
    {
        $list = $this->getEdit('salereturn', ['id' => $id], $data);
        Db::name('salereturnrelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k => $v) {
            $arr['goods_status'] = $v['goods_status'];
            $arr['product_id'] = $v['product_id'];
            $arr['put_number'] = $v['put_number'];
            $arr['pid'] = $id;
            $arr['price'] = $v['price'];
            $arr['discount'] = $v['discount'];
            $arr['discount_price'] = $v['discount_price'];
            $arr['money'] = $v['money'];
            $arr['discount_money'] = $v['discount_money'];
            $this->getAdd('salereturnrelation', $arr);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'stock' => 0
                ];
                $this->getAdd('product_stock', $rel);
            }
        }
        return $list;
    }

    public function getReturnDepot($id,$data)
    {
        return Db::transaction(function () use ($id, $data) {
        Db::name('salereturnrelation')->whereIn('pid',$id)->delete();
        $list =$this->getOne('salereturn','*',['id'=>$id]);
        foreach ($data['goods'] as $k => $v) {
            $arr['goods_status'] = $v['goods_status'];
            $arr['product_id'] = $v['product_id'];
            $arr['put_number'] = $v['put_number'];
            $arr['pid'] = $id;
            $arr['price'] = $v['price'];
            $arr['discount'] = $v['discount'];
            $arr['discount_price'] = $v['discount_price'];
            $arr['money'] = $v['money'];
            $arr['discount_money'] = $v['discount_money'];
            $this->getAdd('salereturnrelation', $arr);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'stock' => $v['put_number']
                ];
                $this->getAdd('product_stock', $rel);
            }else{
                $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'stock',$v['put_number']);
            }
            $flow =[
                'goods_id' =>$v['product_id'],
                'create_time' =>time(),
                'warehouse' =>$data['warehouse'],
                'type' =>'销售退货单',
                'number' =>$list['number'],
                'add_num' =>$v['put_number'],
                'sur_num' =>(isset($stockInfo['stock']) ? $stockInfo['stock'] : 0) + $v['put_number']
            ];
            $this->getAdd('flowing_water',$flow);
        }
        $stock['status'] =3;
        $stock['number'] = $list['number'];
        $stock['create_time'] = $data['create_time'];
        $stock['warehouse'] = $data['warehouse'];
        $stock['maker'] = $data['maker'];
        $stock['type'] = 4;//单据类型  4销售退货单
        $stock['des'] = $data['des'];
        $stock['relation_id'] = $id;
        $this->getAdd('instock', $stock);
        $payment =[
            'customer_id' => $data['kid'],
            'customer_type' => 'user',
            'maker' => $data['maker'],
            'set_account' => $data['set_account'],
            'in_amount' => $data['payment'],
            'des' => $data['des'],
            'create_time' => time(),
            'business_type' => '销售退货单',
            'business_number' => $list['number'],
            'business_time' => $data['create_time']
        ];
        $this->getAdd('set_account_flow', $payment);
        return $this->getEdit('salereturn',['id'=>$id],$data);
        });
    }

    /**
     * 销售退货 详情
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getReturnDetail($id)
    {
        $list = $this->getOne('salereturn', '*', ['id' => $id]);
        $list['goods'] = $this->getselectList('salereturnrelation', '*', ['pid' => $list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $dan = $this->getOne('product', 'commodity_id,color,size', ['id' => $v['product_id']]);
            $goods = $this->getOne('commodity', 'id,name,item,goods_code,unit', ['id' => $dan['commodity_id']]);
            $list['goods'][$k]['name'] = $goods['name'];
            $list['goods'][$k]['item'] = $goods['item'];
            $list['goods'][$k]['goods_code'] = $goods['goods_code'];
            $list['goods'][$k]['color'] = $this->getValue('color3', ['id' => $dan['color']], 'name');
            $list['goods'][$k]['size'] = $this->getValue('color3', ['id' => $dan['size']], 'name');
            $list['goods'][$k]['unit'] = $this->getValue('color1', ['id' => $goods['unit']], 'name');
            $list['goods'][$k]['commodity_id'] = $goods['id'];
        }
        $list['kid_name'] = $this->getValue('user', ['id' => $list['kid']], 'name');
        $list['kid_phone'] = $this->getValue('user', ['id' => $list['kid']], 'phone');
        $list['warehouse_name'] = $this->getValue('warehouse', ['id' => $list['warehouse']], 'name');
        $list['sales_name'] = $this->getValue('admin', ['id' => $list['sales']], 'name');
        $list['set_account_name'] = $this->getValue('set_account', ['id' => $list['set_account']], 'name');
        $list['maker_name'] = $this->getValue('admin', ['id' => $list['maker']], 'name');
        $list['type'] = '销售退货单';
        $list['create_time'] = date('Y-m-d',$list['create_time']);
        switch ($list['status']){
            case 1:
                $list['status_name'] = '已退货';
                break;
            case 2:
                $list['status_name'] = '已撤销';
                break;
            default:
                $list['status_name'] = '草稿';
        }
        return $list;
    }

    /*public function getReturnDepot($id)
    {
        $list = $this->getOne('salereturn', '*', ['id' => $id]);
        $list['goods'] = $this->getselectList('salereturnrelation', '*', ['pid' => $list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $goods = $this->getValue('product', ['id' => $v['product_id']], 'commodity_id');
            $this->getSetDec('product_stock', ['product_id' => $v['product_id']], 'stock', $v['put_number']);
            $this->getSetInc('warehouse_goods', ['warehouse_id' => $list['warehouse'], 'goods_id' => $goods], 'stock', $v['put_number']);
            $stock = $this->getValue('product_stock', ['product_id' => $v['product_id']], 'stock');
            $flow = [
                'goods_id' => $v['product_id'],
                'create_time' => time(),
                'warehouse' => $list['warehouse'],
                'type' => '销售退货单',
                'number' => $list['number'],
                'add_num' => $v['put_number'],
                'sur_num' => $stock + $v['put_number']
            ];
            $this->getAdd('flowing_water', $flow);
        }
        $this->getSetField('salereturn', ['id' => $list['id']], ['status' => 1]);
        $this->getSetField('instock', ['relation_id' => $id, 'type' => 4], ['status' => 2]);
        return 1;
    }*/

    /**
     * 销售退货 撤销
     * @param $id
     * @return array|false|int|\PDOStatement|string|Model
     */
    public function getReturnRevoke($id)
    {
        $list = $this->getOne('salereturn', '*', ['id' => $id]);
        if (in_array($list['status'], [1, 2])) {
            return 1;
        } else {
            $this->getSetField('salereturn', ['id' => $id], ['status' => 2]);
            $this->getSetField('instock', array('relation_id' => $id, 'type' => 4), ['status' => 3]);
            return 2;
        }
    }

    /**
     * 销售退货 删除
     * @param $id
     * @return array|false|int|\PDOStatement|string|Model
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getReturnDel($id)
    {
        $list = $this->getOne('salereturn', '*', ['id' => $id]);
        if (in_array($list['status'], [1, 2])) {
            return 1;
        } else {
            $this->getDel('salereturn', $id);
            Db::name('salereturnrelation')->whereIn('pid', $id)->delete();
            return 2;
        }
    }

    /**
     * 前台收银 列表
     * @param $data
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getCollectList($data)
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where[] = ['create_time', 'between', [$data['start_time'], $data['end_time']]];
        }
        if (!empty($data['sales'])) {
            $where[] = ['sales', '=', $data['sales']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number', 'like', "%" . $data['number'] . "%"];
        }
        $list = $this->getPage('collect', 'id,status,number,create_time,warehouse,maker,payment', $where, 'id desc', $data['page'], $data['size']);
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list['data'][$k]['warehouse_name'] = $this->getValue('warehouse', ['id' => $v['warehouse']], 'name');
            $list['data'][$k]['maker_name'] = $this->getValue('admin', ['id' => $v['maker']], 'name');
            switch ($v['status']) {
                case 1:
                    $list['data'][$k]['status1'] = "已零售";
                    break;
                default:
                    $list['data'][$k]['status1'] = "已撤销";
            }
        }
        return $list;
    }

    /**
     * 前台收银 新增
     * @param $data
     * @return int|string
     */
    public function getCollectAdd($data)
    {
        $arr1 = $this->getAdd('collect', $data);
        foreach ($data['goods'] as $k => $v) {
            $arr['product_id'] = $v['product_id'];
            $arr['put_number'] = $v['put_number'];
            $arr['price'] = $v['price'];
            $arr['pid'] = $arr1;
            $arr['discount'] = $v['discount'];
            $arr['discount_price'] = $v['discount_price'];
            $arr['money'] = $v['money'];
            $arr['discount_money'] = $v['discount_money'];
            $this->getAdd('collectrelation', $arr);
        }
        $payment =[
            'maker' => $data['maker'],
            'set_account' => $data['set_account'],
            'in_amount' => $data['payment'],
            'create_time' => time(),
            'business_type' => '零售单',
            'business_number' => $data['number'],
            'business_time' => $data['create_time'],
        ];
        $this->getAdd('set_account_flow', $payment);
        return $arr1;
    }

    /**
     * 前台收银 详情
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getCollectDetail($id)
    {
        $list = $this->getOne('collect', '*', ['id' => $id]);
        $list['goods'] = $this->getselectList('collectrelation', '*', ['pid' => $list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $dan = $this->getOne('product', 'commodity_id,color,size', ['id' => $v['product_id']]);
            $goods = $this->getOne('commodity', 'name,item,goods_code,unit', ['id' => $dan['commodity_id']]);
            $list['goods'][$k]['name'] = $goods['name'];
            $list['goods'][$k]['item'] = $goods['item'];
            $list['goods'][$k]['goods_code'] = $goods['goods_code'];
            $list['goods'][$k]['color'] = $this->getValue('color3', ['id' => $dan['color']], 'name');
            $list['goods'][$k]['size'] = $this->getValue('color3', ['id' => $dan['size']], 'name');
            $list['goods'][$k]['unit'] = $this->getValue('color1', ['id' => $goods['unit']], 'name');
        }
        $list['warehouse_name'] = $this->getValue('warehouse', ['id' => $list['warehouse']], 'name');
        $list['create_time'] = date('Y-m-d', $list['create_time']);
        $list['maker_name'] =$this->getValue('admin',['id'=>$list['maker']],'name');
        $list['sales_name'] = $this->getValue('admin', ['id' => $list['sales']], 'name');
        $list['sales_phone'] = $this->getValue('admin', ['id' => $list['sales']], 'phone');
        $list['set_account_name'] = $this->getValue('set_account', ['id' => $list['set_account']], 'name');
        $list['status_name'] = self::getCollectStatusAttr($list['status']);
        return $list;
    }

    /**
     * 前台收银 撤销
     * @param $id
     * @return array|false|int|\PDOStatement|string|Model
     */
    public function getCollectRevoke($id)
    {
        $arr = $this->getSetField('collect', ['id' => $id], ['status' => 2]);
        return $arr;
    }
}